package handlers

import (
	"encoding/json"
	"homepage-backend/internal/models"
	"homepage-backend/internal/services"
	"net/http"
	"time"
)

// MusicShareHandler 处理音乐分享请求
func MusicShareHandler(w http.ResponseWriter, r *http.Request) {
	switch r.Method {
	case "POST":
		// 解析请求体
		var share models.MusicShare
		if err := json.NewDecoder(r.Body).Decode(&share); err != nil {
			services.LogError("解析分享请求失败: %v", err)
			http.Error(w, "无效的请求数据", http.StatusBadRequest)
			return
		}

		// 验证必要字段
		if share.Title == "" || share.TrackID == "" || share.ServerURL == "" {
			services.LogError("分享数据不完整: %+v", share)
			http.Error(w, "分享数据不完整，请确保标题、音乐ID、服务器URL都已填写", http.StatusBadRequest)
			return
		}

		// 生成唯一标识符，使用 TrackID + ServerURL + Comment 的组合
		uniqueKey := share.TrackID + "-" + share.ServerURL + "-" + share.Comment
		share.ID = services.GenerateShortID(uniqueKey)
		share.ShareTime = time.Now().Unix()

		// 使用更新后的 SaveShare 函数，它会返回分享ID
		shareID, err := services.SaveShare(share)
		if err != nil {
			services.LogError("保存分享记录失败: %v", err)
			http.Error(w, "保存分享失败", http.StatusInternalServerError)
			return
		}

		// 返回分享ID
		w.Header().Set("Content-Type", "application/json")
		json.NewEncoder(w).Encode(map[string]string{"id": shareID})

	case "GET":
		// 管理端：如果带admin参数，返回全部分享，否则按id查单条
		if r.URL.Query().Get("admin") == "1" {
			shares := services.GetAllShares()
			w.Header().Set("Content-Type", "application/json")
			json.NewEncoder(w).Encode(shares)
			return
		}

		// 获取分享ID
		shareID := r.URL.Query().Get("id")
		if shareID == "" {
			http.Error(w, "缺少分享ID", http.StatusBadRequest)
			return
		}

		// 查找分享
		share, exists := services.GetShare(shareID)
		if !exists {
			http.Error(w, "分享不存在或已过期", http.StatusNotFound)
			return
		}

		// 返回分享信息
		w.Header().Set("Content-Type", "application/json")
		json.NewEncoder(w).Encode(share)

	case "DELETE":
		id := r.URL.Query().Get("id")
		if id == "" {
			http.Error(w, "缺少分享ID", http.StatusBadRequest)
			return
		}
		if err := services.DeleteShare(id); err != nil {
			http.Error(w, "删除失败", http.StatusInternalServerError)
			return
		}
		w.Write([]byte("ok"))
		return
	default:
		http.Error(w, "不支持的请求方法", http.StatusMethodNotAllowed)
	}
}
